/*
 * @Description:
 * @Author: cgt
 * @Date: 2021-12-23 14:05:56
 * @LastEditors: cgt
 * @LastEditTime: 2021-12-28 19:30:10
 */
/**
 * @module utils/GeometryUtil
 * @desc 图形操作工具
 */

import { flatten } from './ArrayUtil';

/**
 * 获取图形边界
 * @param {geometry} geometry 图形坐标
 */
export function getExtent(geometry) {
  var coordinates = [];
  if (Array.isArray(geometry)) {
    flatten(geometry, coordinates);
  } else {
    flatten(geometry.coordinates, coordinates);
  }
  // 奇数位
  var x = coordinates.filter((item, index) => index % 2 === 0);
  // 偶数位
  var y = coordinates.filter((item, index) => index % 2 === 1);
  var xmin = Math.min.apply(null, x),
    xmax = Math.max.apply(null, x),
    ymin = Math.min.apply(null, y),
    ymax = Math.max.apply(null, y);
  return [xmin, ymin, xmax, ymax];
}

/**
 * 获取图形中心点
 * @param {geometry} geometry 图形坐标
 */
export function getCenter(geometry) {
  var extent = getExtent(geometry);
  return [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2];
}

// 是否包含
export function isContains(big, small, similarity) {
  // 判断重合面积占小区域总面积的百分比
  // eslint-disable-next-line init-declarations
  let intersect;
  try {
    intersect = turf.intersect(big, small);
  } catch (e) {
    if (
      (big.geometry.type === 'Polygon' || big.geometry.type === 'MutliPolygon') &&
        (small.geometry.type === 'Polygon' || small.geometry.type === 'MutliPolygon')
    ) {
      let simpleBig = turf.truncate(big, { precision: 10 });
      let simpleSmall = turf.truncate(small, { precision: 10 });
      intersect = turf.intersect(simpleBig, simpleSmall);
    } else {
      return false;
    }
  }
  if (intersect) {
    let intersectArea = turf.area(intersect);
    let smallArea = turf.area(small);
    let percent = intersectArea / smallArea;
    return percent >= (similarity || 0.8);
  }
  return false;

}
